package a2022.a20220913;

import java.util.*;


/**
 * @author lenovo
 * @date 2022/9/13
 */
public class a {
    public static void main(String[] args) {
//        System.out.println(maximumSwap(19931227));
        System.out.println(maximumSwap2(19931227));
    }

    public static int maximumSwap(int num) {
//        排序且转list
//        List<Character> collect = (num + "").chars().
//                mapToObj(c -> (char) c).
//                sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        String s = num + "";
        char[] chars = s.toCharArray();
        char[] newchars = Arrays.copyOf(chars, s.length());
        Arrays.sort(chars);
        int max = -1;
        int subMax = -1;
        int sub = -1;
        for (int i = 0, j = chars.length - 1; i < chars.length; i++, j--) {
            if (sub == newchars[i]) {
                subMax = i;
            }
            if (chars[j] > newchars[i] && max == -1) {
                max = i;
                sub = chars[j];
            }
        }
        if (max == -1)return num;
        sub = newchars[subMax];
        newchars[subMax] = newchars[max];
        newchars[max] = (char) sub;
        return Integer.parseInt(new String(newchars));
    }

    public static int maximumSwap2(int num) {
        List<Integer> list = new ArrayList<>();
        while (num != 0) {
            list.add(num % 10); num /= 10;
        }
        int n = list.size(), ans = 0;
        int[] idx = new int[n];
        for (int i = 0, j = 0; i < n; i++) {
            if (list.get(i) > list.get(j)) j = i;
            idx[i] = j;
        }
        for (int i = n - 1; i >= 0; i--) {
            if (list.get(idx[i]) != list.get(i)) {
                int c = list.get(idx[i]);
                list.set(idx[i], list.get(i));
                list.set(i, c);
                break;
            }
        }
        for (int i = n - 1; i >= 0; i--) ans = ans * 10 + list.get(i);
        return ans;
    }

}
